﻿using System;
using System.Collections.Generic;
using System.Web;
using System.IO;


namespace CCPSIP.Sticker
{
    /// <summary>CCPSIP_033：機器人貼圖檔案列表 API</summary>
    /// idHeader = 裝置 UUID 前八碼。
    /// checkcode = 裝置限時驗證碼。

    public class robot_sticker_list : IHttpHandler
    {
        private const string kStickerDirRobot = @"\\203.69.132.77\Sip-Line\Robot";


        public void ProcessRequest(HttpContext context)
        {
            HttpRequest req = context.Request;
            HttpResponse resp = context.Response;
            resp.ContentType = "text/plain";
            resp.ContentEncoding = System.Text.Encoding.UTF8;
            DateTime reqTime = DateTime.Now;
            string resultStr = "";

            try
            {
                //【01】取得POST參數，驗證身分
                //
                string idHeader = req.Form["idHeader"];
                string checkcode = req.Form["checkcode"];

                SipUserInfo userInfo = SipKit.GetUserInfo(idHeader, checkcode, req);
                if (userInfo == null)
                {
                    throw new Exception("Error_01: Cannot identify this device");//無法識別此裝置
                }


                //【02】取得可用的機器人權限
                //
                RobotInfo[] robots = RobotKit.getRobots(userInfo);


                //【03】切換網域身分存取資料夾
                //
                List<RobotDirInfo> robotDirList = new List<RobotDirInfo>();

                string tempCode = HashKit.getHashStr("CCPSIP-20121030", HashType.SHA512).Substring(6, 20);

                using (new Tools.Impersonator("iSIPAgent", "CCP.COM.TW", tempCode))
                {
                    //【04】機器人貼圖資料夾
                    //
                    foreach (RobotInfo robot in robots)
                    {
                        string robotDir = string.Format(@"{0}\{1}", kStickerDirRobot, robot.ROBOT_ID);
                        if (Directory.Exists(robotDir))
                        {
                            RobotDirInfo rInfo = new RobotDirInfo(robot.ROBOT_ID, robotDir);
                            robotDirList.Add(rInfo);
                        }
                    }
                }


                //【99】回傳結果
                //
                resp.ContentType = "application/json";
                resp.Charset = null;
                fastJSON.JSON.Instance.Parameters.EnableAnonymousTypes = true;
                resultStr = fastJSON.JSON.Instance.ToJSON(robotDirList.ToArray());
            }
            catch (Exception ex)
            {
                resp.ContentType = "application/xml";
                resultStr = ChrisKit.Ex2Xml(ex, false);
            }
            finally
            {
                int contentLength = resp.ContentEncoding.GetByteCount(resultStr);
                resp.AppendHeader("Content-Length", contentLength.ToString());
                resp.Write(resultStr);
                resp.Flush();
                resp.Close();
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }


        #region 資料夾檔案簡易資訊(機器人)

        private class RobotDirInfo
        {
            private string _ROBOT_ID;
            private List<EasyDirInfo> _DirList;

            public string ROBOT_ID { get { return this._ROBOT_ID; } }
            public List<EasyDirInfo> DirList { get { return this._DirList; } }

            public RobotDirInfo(string robotID, string robotDir)
            {
                _ROBOT_ID = robotID;
                _DirList = new List<EasyDirInfo>();

                DirectoryInfo dInfo = new DirectoryInfo(robotDir);
                foreach (DirectoryInfo subDir in dInfo.GetDirectories())
                {
                    EasyDirInfo eDirInfo = new EasyDirInfo(subDir, "*.png");
                    if (eDirInfo.FileList.Count > 0)
                        _DirList.Add(eDirInfo);
                }
                _DirList.Sort();
            }
        }


        [Serializable()]
        private class EasyDirInfo : IComparable
        {
            private string _Name;
            private List<EasyFileInfo> _FileList;

            public string Name { get { return this._Name; } }
            public List<EasyFileInfo> FileList { get { return this._FileList; } }

            public EasyDirInfo(DirectoryInfo dInfo, string searchPattern)
            {
                _Name = dInfo.Name;
                _FileList = new List<EasyFileInfo>();
                foreach (FileInfo fInfo in dInfo.GetFiles(searchPattern))
                {
                    EasyFileInfo eFileInfo = new EasyFileInfo(fInfo);
                    _FileList.Add(eFileInfo);
                }
                _FileList.Sort();
            }

            public int CompareTo(object obj)
            {
                if (obj is EasyDirInfo)
                {
                    EasyDirInfo dInfo = (EasyDirInfo)obj;
                    return this.CompareTo(dInfo);
                }
                else
                {
                    throw new Exception("ERROR_CANNOT_COMPARE");
                }
            }

            public int CompareTo(EasyDirInfo dInfo)
            {
                return _Name.CompareTo(dInfo._Name);
            }
        }


        [Serializable()]
        private class EasyFileInfo : IComparable
        {
            private string _Name;
            private long _Length;
            private DateTime _LastWriteTime;

            public string Name { get { return this._Name; } }
            public long Length { get { return this._Length; } }
            public DateTime LastWriteTime { get { return this._LastWriteTime; } }

            public EasyFileInfo(FileInfo fInfo)
            {
                _Name = fInfo.Name;
                _Length = fInfo.Length;
                _LastWriteTime = fInfo.LastWriteTime;
            }

            public int CompareTo(object obj)
            {
                if (obj is EasyFileInfo)
                {
                    EasyFileInfo fInfo = (EasyFileInfo)obj;
                    return this.CompareTo(fInfo);
                }
                else
                {
                    throw new Exception("ERROR_CANNOT_COMPARE");
                }
            }

            public int CompareTo(EasyFileInfo fInfo)
            {
                return _Name.CompareTo(fInfo._Name);
            }
        }

        #endregion

    }
}
